﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OrmAuto;

public partial class Adm_DB_SQLDB : System.Web.UI.Page
{
		LayerBaseSql mQuerySql = new LayerBaseSql();
		string sql = string.Empty;
		
		private string mConnSTRING_NAME ="baseConnectionString";

		protected void Page_Load(object sender, EventArgs e)
		{
				bindSchemaTabelle(null); 
		}

		private void bindSchemaTabelle(string sortExpr)
		{
				try
				{
						using (var dt = mQuerySql.getTabelleDB(mConnSTRING_NAME))
				  {
								if(! string.IsNullOrEmpty(sortExpr) )
										dt.DefaultView.Sort =sortExpr ;
								   
								this.GridViewTabelle.DataSource = dt;
								this.GridViewTabelle.DataBind();
							}	
				}
				catch (Exception ex)
				{
						LabelMsgTabs.Text = ex.Message;
				}
		}

		protected void ButtonExecNoRet_Click(object sender, EventArgs e)
		{
				sql = txtSQL.Text;
				if (string.IsNullOrEmpty(sql)) return;

				try
				{
						using (var conn = mQuerySql.getSQLConnection(mConnSTRING_NAME))
						{
								var rea = mQuerySql.exeqSQLNoRet(sql, System.Data.CommandType.Text, conn);
								
										LabelMsg.Text = "Eseguito,affetti : " + rea.ToString() + " (" + DateTime.Now.ToLongTimeString();								
						}
				}
				catch (Exception ex)
				{
						LabelMsg.Text ="Err : "+ex.Message ; 
				}
				
				
		}//fM

		protected void ButtonExec_Click(object sender, EventArgs e)
		{
				sql = txtSQL.Text;
				if (string.IsNullOrEmpty(sql)) return;

				try
				{
						using (var conn = mQuerySql.getSQLConnection(mConnSTRING_NAME))
						{
								if (!mQuerySql.tryToOpenConn(conn)) { LabelMsg.Text = "Conn chiusa"; return; }
								using (var tabel = mQuerySql.exeqSQLTable(sql, System.Data.CommandType.Text, conn))
								{								  								     
										this.GridViewRes.DataSource = tabel;
										this.GridViewRes.DataBind();

										LabelMsg.Text = "Eseguito,affetti : " + tabel.Rows.Count.ToString() + " (" + DateTime.Now.ToLongTimeString();
								}
						}
				}
				catch (Exception ex)
				{
						LabelMsg.Text = "Err : " + ex.Message; 
				}
		}//fM

		protected void GridViewTabelle_PageIndexChanging(object sender, GridViewPageEventArgs e)
		{
				GridViewTabelle.PageIndex = e.NewPageIndex;
				bindSchemaTabelle(null);
		}//fM

		protected void GridViewTabelle_Sorting(object sender, GridViewSortEventArgs e)
		{ 
		  var dir = e.SortDirection == SortDirection.Ascending ? "desc":"asc";  
				bindSchemaTabelle(e.SortExpression + " " + dir);

		}
		
}//fC
